/**
 * 	write on 2005-10-9 11:24:24.
 */
package org.nanhill.xsheet.spring;

import java.util.Map;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.nanhill.support.spring.mvc.AbstractExcelView;
import org.nanhill.xsheet.model.XSheetModel;
import org.nanhill.xsheet.output.excel.DefaultExcelOutputBuilder;
import org.nanhill.xsheet.output.excel.ExcelOutputBuilder;
import org.nanhill.xsheet.output.excel.AbstractExcelOutputDirector;
import org.nanhill.xsheet.output.excel.PushCellExcelOutputDirector;

/**
 * @author alin
 * 
 */
public class XSheetExcelView extends AbstractExcelView {
	private static final Log logger = LogFactory.getLog(XSheetExcelView.class);

	public static final String NH_SHEET_MODEL = "NH_SHEET_MODEL";

	protected HSSFWorkbook workbook;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.web.servlet.view.document.AbstractExcelView#buildExcelDocument(java.util.Map,
	 *      org.apache.poi.hssf.usermodel.HSSFWorkbook,
	 *      javax.servlet.http.HttpServletRequest,
	 *      javax.servlet.http.HttpServletResponse)
	 */
	protected void buildExcelDocument(Map model, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		logger.info("start build excel document...");
		ExcelOutputBuilder builder = new DefaultExcelOutputBuilder();
		builder.setModel((XSheetModel) model.get(NH_SHEET_MODEL));
		AbstractExcelOutputDirector director = new PushCellExcelOutputDirector();
		director.setBuilder(builder);
		director.construct();
		this.workbook = builder.getProduct();
	}
	
	protected void renderMergedOutputModel(Map model,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		buildExcelDocument(model, request, response);
		response.setContentType(getContentType());
		ServletOutputStream out = response.getOutputStream();
		workbook.write(out);
		out.flush();
	}

}
